package com.jarveis.frame.io;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 * FTP传输
 * 
 * @author liuguojun
 */
public class LocalTransfer implements NetTransfer {

	private static final Logger logger = Logger.getLogger(LocalTransfer.class);
	private String host;
	
	public LocalTransfer(String host) {
		this.host = host;
	}

	public boolean connect() throws Exception {

		return true;
	}

	public boolean disconnect() throws Exception {

		return true;
	}

	public boolean download(String remote, String local) throws Exception {
		FileUtil.copyFile(host + remote, local);

		return true;
	}
	
	public byte[] download(String remote) throws Exception {
		return FileUtils.readFileToByteArray(new File(host + remote));
	}

	public boolean upload(String local, String remote) throws Exception {
		File localFile = new File(local);
		if (localFile.isDirectory()) {
			return true;
		}

		// 对远程目录的处理
		if ((host + remote).contains("/")) {
			// 创建服务器远程目录结构，创建失败直接返回
			if (!CreateDirecroty(remote)) {
				return false;
			}
		}

		FileUtils.copyFile(new File(local), new File(host + remote));
		logger.info("upload file success. --->" + host + remote);

		return true;
	}
	
	public boolean upload(byte[] byteArr, String remote) throws Exception {
		FileUtils.writeByteArrayToFile(new File(host + remote), byteArr);
		return true;
	}

	public boolean CreateDirecroty(String remote) throws Exception {
		FileUtils.forceMkdir(new File(host + remote));
		return true;
	}

	public boolean remove(String remote) throws Exception {
		File file = new File(host + remote);
		return file.delete();
	}

}
